package com.wise.service.portal.content.applicationarticle;

import cn.hutool.core.bean.BeanUtil;
import com.wise.entities.content.ApplicationArticle;
import com.wise.entities.content.ArticleStatus;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.exception.LogicException;
import com.wise.summer.v1.portal.content.applicationarticle.GetApplicationArticleById;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.List;

import static com.wise.model.content.ContentErrMsgs.Err_001600250007;
import static com.wise.model.content.ContentErrMsgs.Err_001600250017;

/**
 * @author hejiawei
 * @date 2020/10/27 12:52
 */
@Service
@SummerService
public class GetApplicationArticleService implements SummerServiceBean<GetApplicationArticleById> {
    @Override
    public void sum(GetApplicationArticleById summer) {
        List<ApplicationArticle> applicationArticles = getArticleList(summer);
        if (applicationArticles.isEmpty()) {
            throw new LogicException(this.getClass(), Err_001600250007);
        } else if (applicationArticles.get(0).getState().equals(ArticleStatus.NOTPUBLISH.value())) {
            throw new LogicException(this.getClass(), Err_001600250017);
        } else {
            GetApplicationArticleById.Result articleResult = new GetApplicationArticleById.Result();
            BeanUtil.copyProperties(applicationArticles.get(0), articleResult);
            summer.setSummerResult(articleResult);
        }
    }

    /**
     * 获取查询列表
     *
     * @param model 入参
     * @return 列表
     */
    private List<ApplicationArticle> getArticleList(GetApplicationArticleById model) {
        SqlSelect selectByAlias = SqlSelect.selec("*")
                .fromClassName(ApplicationArticle.class)
                .eq(ApplicationArticle.ALIAS, model.getId());
        List<ApplicationArticle> articleList = DaoList.s(ApplicationArticle.class, selectByAlias);
        // 如果根据别名查不到，则根据id查询
        if (articleList.isEmpty()) {
            SqlSelect selectArticle = SqlSelect.selec("*")
                    .fromClassName(ApplicationArticle.class)
                    .eq(ApplicationArticle._id, model.getId());
            return DaoList.s(ApplicationArticle.class, selectArticle);
        } else {
            return articleList;
        }
    }
}
